<template>
  <view class="exam-container">
    <wd-navbar 
      :title="paperBaseInfo.title" 
      custom-class="navbar-custom" 
      :bordered="false" 
      fixed 
      placeholder 
      safeAreaInsetTop
      left-arrow
      @click-left="goBack"
    ></wd-navbar>
    <!-- 题目列表 -->
    <scroll-view class="exam-content" scroll-y>
      <!-- 空状态 -->
      <view v-if="questionList.length == 0" class="empty-state">
        <text class="text-[35rpx] color-[#969799]">{{ type == 'wrongExercise' ? '暂无错题' : '暂无题目' }}</text>
      </view>

      <!-- 题目 -->
      <view
        v-for="(question, index) in questionList"
        :key="question.questionId"
        class="question-item"
      >
        <!-- 题目标题 -->
        <view class="question-title">
          {{ index + 1 }}. <text v-if="question.score">（{{ question.score }}分）</text>{{ question.text }}
        </view>

        <!-- 判断题 cate == 1 -->
        <view v-if="question.cate == 1">
          <wd-radio-group v-model="question.userAnswer" shape="dot" icon-placement="left" checked-color="#4cd964">
            <wd-radio
              v-for="option in question.options"
              :key="option.optionId"
              :value="option.key"
            >
              {{ option.text }}
            </wd-radio>
          </wd-radio-group>
        </view>

        <!-- 单选题 cate == 2 -->
        <view v-if="question.cate == 2">
          <wd-radio-group v-model="question.userAnswer" shape="dot" icon-placement="left" checked-color="#4cd964">
            <wd-radio
              v-for="option in question.options"
              :key="option.optionId"
              :value="option.key"
            >
              {{ option.key }}. {{ option.text }}
            </wd-radio>
          </wd-radio-group>
        </view>

        <!-- 多选题 cate == 4 -->
        <view v-if="question.cate == 4">
          <wd-checkbox-group v-model="question.userAnswer" shape="square" icon-placement="left" checked-color="#4cd964">
            <wd-checkbox
              v-for="option in question.options"
              :key="option.optionId"
              :model-value="option.key"
            >
              {{ option.key }}. {{ option.text }}
            </wd-checkbox>
          </wd-checkbox-group>
        </view>
      </view>
    </scroll-view>

    <!-- 提交按钮（有题目时才显示） -->
    <view v-if="questionList.length > 0" class="exam-footer">
      <wd-button custom-class="submit-btn" size="large" block @click="submitExam">
        <text class="text-[40rpx] font-bold line-height-[56rpx] color-[#282828] text-shadow-[2rpx_0rpx_2rpx_rgba(0,0,0,0)]">已完成答题，提交试卷！</text>
      </wd-button>
    </view>

    <!-- 右下角倒计时（错题练习不显示，且有题目时才显示） -->
    <view v-if="type != 'wrongExercise' && questionList.length > 0" class="countdown-float">
      <view class="countdown-circle">
        <view class="countdown-time" style="border-bottom: 1px solid #e5e5e5;">{{ minutes }}M</view>
        <view class="countdown-time">{{ seconds }}S</view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { 
  paperDetail,
  answerQuestion, //回答问题
  cancelAnswer, //取消答案
  submitPaper, //提交考试
  everyday10, //每日10题
  wrongExercise, //错题练习
} from '@/api/exam.js'

const paper_id = ref(''); // 试卷ID
const exam_id = ref(''); // 考试ID
const type = ref(''); // 类型：everyday10, wrongExercise 等
const paperBaseInfo = ref({}) // 试卷基础信息
const questionList = ref([]) // 题目列表

// 字母表，用于生成选项 key
const OPTION_KEYS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K']

// 用于存储多选题的上一次选择状态，以便比对变化
const previousMultipleAnswers = ref({})

// 根据 type 获取试卷数据
const fetchPaperData = () => {
  let apiPromise = null
  
  // 根据不同的 type 调用不同的接口
  if (type.value == 'everyday10') { // 每日10题
    apiPromise = everyday10()
  } else if (type.value == 'wrongExercise') { // 错题练习
    apiPromise = wrongExercise({ page: 1 })
  } else { // 默认调用 paperDetail
    apiPromise = paperDetail({
      paper_id: paper_id.value
    })
  }
  
  return apiPromise
}

onLoad((options) => {
  paper_id.value = options.id || options.paper_id || ''
  type.value = options.type || ''
  // 如果是智能测试
  if (type.value == 'test') {
    paperBaseInfo.value.title = '智能测试'
    paper_id.value = 1000 //智能测试试卷ID
  }
  
  fetchPaperData().then(res => {
    // 处理空数据情况（code=101时返回空数组）
    if (!res || Array.isArray(res) || !res.question || res.question.length == 0) {
      questionList.value = []
      paperBaseInfo.value = {
        title: type.value == 'wrongExercise' ? '错题练习' : type.value == 'test' ? '智能测试' : '考试答题'
      }
      return
    }
    
    exam_id.value = res.exam_id
    paperBaseInfo.value = res.info || {}
    // 如果是每日10题或错题练习，需要给paper_id赋值
    if (type.value == 'everyday10' || type.value == 'wrongExercise') {
      paper_id.value = res.info?.paper_id || ''
    }
    // 如果是错题练习，需要添加标题，防止没数据
    if (type.value == 'wrongExercise' && !res?.info?.title) {
      paperBaseInfo.value.title = '错题练习'
    }
    
    
    // 设置倒计时（使用试卷的 duration，已经是秒为单位）- 错题练习不需要倒计时
    if (res.info?.remain_duration && type.value != 'wrongExercise') {
      totalSeconds.value = res.info.remain_duration
    }
    
    // 转换题目数据
    questionList.value = (res.question || []).map(item => {
      const question = {
        questionId: item.question_id || item.id,
        cate: item.cate, // 1=判断, 2=单选, 4=多选
        text: item.text,
        image: item.image,
        score: item.score,
        options: [],
        userAnswer: item.cate == 4 ? [] : '', // 多选题用数组，其他用字符串
      }
      
      // 处理选项
      if (item.cate == 1) {
        // 判断题：正确=1，错误=0
        question.options = [
          { optionId: 1, key: 'A', text: '正确' },
          { optionId: 0, key: 'B', text: '错误' },
        ]
      } else {
        // 单选题/多选题：为每个选项添加 key (A, B, C, D...)
        question.options = (item.options || []).map((opt, index) => ({
          optionId: opt.option_id || opt.id,
          key: OPTION_KEYS[index],
          text: opt.text,
          image: opt.image,
        }))
      }
      
      // 回显用户之前的答案（防止回显时触发接口调用）
      if (item.user_answer && item.user_answer.length > 0) {
        if (item.cate == 4) {
          // 多选题：user_answer 是多个 optionId 的数组，需要转换为多个 key
          question.userAnswer = item.user_answer.map(answerId => {
            const option = question.options.find(opt => opt.optionId == answerId)
            return option ? option.key : null
          }).filter(key => key != null)
        } else {
          // 判断题和单选题：user_answer 是单个 optionId 的数组，只取第一个
          const answerId = item.user_answer[0]
          const option = question.options.find(opt => opt.optionId == answerId)
          if (option) {
            question.userAnswer = option.key
          }
        }
      }
      
      // 初始化多选题的上一次状态（使用回显后的状态，防止第一次变化被视为新增）
      if (item.cate == 4) {
        previousMultipleAnswers.value[item.question_id] = [...question.userAnswer]
      }
      
      return question
    })
    
    // 数据加载完成后，开始监听每个题目的答案变化
    if (questionList.value.length > 0) {
      setupAnswerWatchers()
    }
  }).catch(err => {
  })
})

definePage({
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '考试答题',
  },
})

// 倒计时（秒）
const totalSeconds = ref(30 * 60) // 30分钟，会根据试卷设置动态调整
let timer = null

// 倒计时分钟和秒数
const minutes = computed(() => Math.floor(totalSeconds.value / 60))
const seconds = computed(() => totalSeconds.value % 60)

// 开始倒计时
const startTimer = () => {
  timer = setInterval(() => {
    if (totalSeconds.value > 0) {
      totalSeconds.value--
    } else {
      clearInterval(timer)
      // uni.showToast({
      //   title: '时间到，自动提交',
      //   icon: 'none',
      // })
      setTimeout(() => {
        doSubmit()
      }, 500)
    }
  }, 1000)
}

// 设置答案变化监听器
const setupAnswerWatchers = () => {
  questionList.value.forEach((question, index) => {
    watch(
      () => question.userAnswer,
      (newAnswer, oldAnswer) => {
        // 判断题和单选题：直接调用 answerQuestion
        if (question.cate == 1 || question.cate == 2) {
          handleSingleChoiceAnswer(question, newAnswer)
        } 
        // 多选题：需要比对变化，确定是添加还是删除选项
        else if (question.cate == 4) {
          handleMultipleChoiceAnswer(question, newAnswer, oldAnswer)
        }
      },
      { deep: true }
    )
  })
}

// 处理判断题和单选题的答案
const handleSingleChoiceAnswer = (question, answer) => {
  if (!answer) return // 空答案不处理
  
  // 根据 key 找到对应的 optionId
  const selectedOption = question.options.find(opt => opt.key == answer)
  if (!selectedOption) return
  
  const requestData = {
    exam_id: exam_id.value,
    paper_id: paper_id.value,
    question_id: question.questionId,
    answer_id: selectedOption.optionId,
  }
  
  answerQuestion(requestData).then(res => {
  }).catch(err => {
    uni.showToast({
      title: '答案提交失败',
      icon: 'none'
    })
  })
}

// 处理多选题的答案
const handleMultipleChoiceAnswer = (question, newAnswer, oldAnswer) => {
  const questionId = question.questionId
  const previousAnswer = previousMultipleAnswers.value[questionId] || []
  
  // 找出新增的选项（在 newAnswer 中但不在 previousAnswer 中）
  const addedOptions = newAnswer.filter(key => !previousAnswer.includes(key))
  
  // 找出删除的选项（在 previousAnswer 中但不在 newAnswer 中）
  const removedOptions = previousAnswer.filter(key => !newAnswer.includes(key))
  
  // 处理新增的选项 - 调用 answerQuestion
  addedOptions.forEach(key => {
    const selectedOption = question.options.find(opt => opt.key == key)
    if (!selectedOption) return
    
    const requestData = {
      exam_id: exam_id.value,
      paper_id: paper_id.value,
      question_id: question.questionId,
      answer_id: selectedOption.optionId,
    }
    
    answerQuestion(requestData).then(res => {
    }).catch(err => {
    })
  })
  
  // 处理删除的选项 - 调用 cancelAnswer
  removedOptions.forEach(key => {
    const deselectedOption = question.options.find(opt => opt.key == key)
    if (!deselectedOption) return
    
    const requestData = {
      exam_id: exam_id.value,
      paper_id: paper_id.value,
      question_id: question.questionId,
      answer_id: deselectedOption.optionId,
    }
    
    cancelAnswer(requestData).then(res => {
    }).catch(err => {
    })
  })
  
  // 更新上一次的答案状态
  previousMultipleAnswers.value[questionId] = [...newAnswer]
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 提交试卷
const submitExam = () => {
  // 检查是否全部完成
  // let unansweredCount = 0
  // questionList.value.forEach((question) => {
  //   if (question.cate == 4) {
  //     // 多选题 (cate == 4)
  //     if (question.userAnswer.length == 0) {
  //       unansweredCount++
  //     }
  //   } else {
  //     // 单选、判断 (cate == 1 或 2)
  //     if (!question.userAnswer) {
  //       unansweredCount++
  //     }
  //   }
  // })

  // if (unansweredCount > 0) {
  //   uni.showModal({
  //     title: '提示',
  //     content: `还有 ${unansweredCount} 道题未作答，确定要提交吗？`,
  //     success: (res) => {
  //       if (res.confirm) {
  //         doSubmit()
  //       }
  //     },
  //   })
  // } else {
    doSubmit()
  // }
}

// 执行提交
const doSubmit = () => {
  // 停止倒计时
  if (timer) {
    clearInterval(timer)
  }

  // 计算考试用时（用于显示）
  let usedMinutes = 0
  let usedSecondsRemainder = 0
  
  // 错题练习模式不计算用时
  if (type.value != 'wrongExercise') {
    const totalDuration = paperBaseInfo.value.remain_duration || 30 * 60 // 总时长（秒）
    const usedSeconds = totalDuration - totalSeconds.value
    usedMinutes = Math.floor(usedSeconds / 60)
    usedSecondsRemainder = usedSeconds % 60
  }

  const submitData = {
    exam_id: exam_id.value,
    paper_id: paper_id.value,
  }

  // console.log('提交考试：', submitData)

  // uni.showLoading({
  //   title: '提交中...',
  // })
  
  // 调用提交考试接口
  submitPaper(submitData).then(res => {
    uni.hideLoading()
    // console.log('考试提交成功：', res)
    
    // 跳转到成绩页面，传递成绩数据
    uni.navigateTo({
      url: `/pages-children/examResult/index?duration=${res.duration || 0}&score=${res.score || 0}`, //这里的数据是提交后接口返回的
    })
  }).catch(err => {
    uni.hideLoading()
    // console.error('考试提交失败：', err)
    uni.showToast({
      title: '提交失败',
      icon: 'none'
    })
  })
}

onMounted(() => {
  // 错题练习模式不启动倒计时
  if (type.value != 'wrongExercise') {
    startTimer()
  }
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style lang="scss" scoped>
.exam-container {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 40rpx;
}

.exam-content {
  padding: 30rpx 30rpx 20rpx;
  box-sizing: border-box;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 200rpx 0;
}

.question-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.question-title {
  font-size: 30rpx;
  color: #323233;
  line-height: 1.6;
  margin-bottom: 20rpx;
}

:deep(.wd-radio) {
  display: flex !important;
  justify-content: flex-end !important;
  align-items: center !important;
  // flex-direction: row !important;
  padding: 16rpx 0 !important;
}
:deep(.wd-checkbox) {
  display: flex !important;
  justify-content: flex-start !important;
  align-items: center !important;
  // flex-direction: row !important;
  padding: 16rpx 0 !important;
}
:deep(.wd-radio__shape) {
  margin-right: 20rpx !important;
}



.exam-footer {
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  :deep(.submit-btn) {
    background-image: url('/static/images/bg1.png') !important;
    background-size: cover !important;
    background-position: center !important;
    border: none !important;
    color: #fff !important;
    font-weight: 600 !important;
  }
}

.countdown-float {
  position: fixed;
  right: 30rpx;
  bottom: calc(170rpx + env(safe-area-inset-bottom));;
  z-index: 100;
}

.countdown-circle {
  width: 128rpx;
  height: 128rpx;
  border-radius: 50%;
  background-color: #fff;
  border: 4rpx solid #4cd964;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.countdown-time {
  font-size: 32rpx;
  font-weight: bold;
  color: #323233;
  line-height: 50rpx;
}
</style>
